<template>
  <div class="coinrevenue-list report-container"
       id="coinrevenue-des">
    <Row type='flex'
         justify="space-between"
         class="coinrevenue-list-edit">
      <Row type='flex'
           align='middle'>
        <Col>
        <span class="concrete-data">时间：</span>
        <datePickerYmd @on-change="searchCoin"
                       :selectDateType.sync='selectDateType'
                       :dataType="dataType"
                       v-model="timeDate"
                       :dateOption="dateOption"
                       style="display:inline-block"></datePickerYmd>
        </Col>
        <Row type='flex'
             align='middle'
             class="export-btn">
          <Col><span>门店名称：</span></Col>
          <Col>
          <vueTreeselectChoice :multiple="true"
                               ref="vueTreeselectChoice"
                               @input="handleShop"
                               @on-api-finish="apiFinish"
                               permissionCode="moms:report:coinrevenue"
                               v-model="ShopValue"></vueTreeselectChoice>
          <!-- <vueTreeselectShop :shopList.sync="searchObj.shopId"
                             @id-change="searchCoin"
                             :statusList.sync="statusList"
                             permissionCode="moms:report:coinrevenue"
                             v-model="testValue"></vueTreeselectShop> -->
          </Col>
          <Col>
          <Button type="primary"
                  class="coinrevenue-btn export-btn"
                  @click="searchCoin">查询</Button>
          </Col>
        </Row>
      </Row>
      <Col class="ropdown"
           v-if="hasPermission('moms:report:coinrevenueexport')">
      <Dropdown trigger="click"
                placement="bottom-start"
                class="coinrevenue-btn export-btn"
                style="margin-right:-80px;width:160px"
                @on-click="DropdownItemn">
        <Button class="check_all"
                style="width:80px;margin-right:20px">导出
          <Icon type="ios-arrow-down"></Icon>
        </Button>
        <DropdownMenu slot="list"
                      style="text-align:center">
          <DropdownItem name="coinRevenueDaily">游戏币收入汇总表</DropdownItem>
          <DropdownItem name="coinRevenueDetail">游戏币收入明细表</DropdownItem>
        </DropdownMenu>
      </Dropdown>
      </Col>
    </Row>
    <Table stripe
           ref="rowSpanTable"
           :height="this.tableHeight"
           :loading="isloading"
           class="table-list"
           border
           :columns="columns"
           :data="resData">
      <template slot-scope="{ row }"
                slot="depositNum">
        <saasPoptip trigger="hover"
                    v-if="selectDateType==='date'"
                    content="上期期末存币数+当期售赠币总数-当期机台吸币数">
          <span class="deposit">{{row.depositNum}}</span>
        </saasPoptip>
        <saasPoptip trigger="hover"
                    v-if="selectDateType==='month'"
                    :content='depositNnmMonth'>
          <span class="deposit">{{row.depositNum}}</span>
        </saasPoptip>
        <saasPoptip trigger="hover"
                    v-if="selectDateType==='year'"
                    :content='depositNnmDate'>
          <span class="deposit">{{row.depositNum}}</span>
        </saasPoptip>
      </template>
      <template slot-scope="{ row }"
                slot="unitCoinAmount">
        <saasPoptip trigger="hover"
                    v-if="selectDateType==='date'"
                    content="（上期期末存币金额+当期游戏币营收）/（上期期末存币总数+当期游戏币售赠数）">
          <span class="deposit">{{row.unitCoinAmount}}</span>
        </saasPoptip>
        <saasPoptip trigger="hover"
                    v-if="selectDateType==='month'"
                    :content='depositNnmMonth'>
          <span class="deposit">{{row.unitCoinAmount}}</span>
        </saasPoptip>
        <saasPoptip trigger="hover"
                    v-if="selectDateType==='year'"
                    :content='depositNnmDate'>
          <span class="deposit">{{row.unitCoinAmount}}</span>
        </saasPoptip>
      </template>
      <template slot-scope="{ row }"
                slot="depositAmount">
        <saasPoptip trigger="hover"
                    content="期末存币总数*单位币值">
          <span class="deposit">{{row.depositAmount}}</span>
        </saasPoptip>
      </template>
      <template slot-scope="{ row }"
                slot="action">
        <i class="iconsys icondetail"
           title="查看详情"
           @click='skipDetail(row.shopId)'></i>
      </template>
    </Table>
    <div class="page-box"
         style="margin-top: 20px">
      <Page :total="total"
            ref="pages"
            :current.sync="searchObj.offset"
            :page-size="searchObj.limit"
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
            show-sizer
            :page-size-opts="$pageSizeOpts"
            show-total />
    </div>
    <down-center ref="downCenterRef"
                 perms="moms:report:coinrevenue"
                 v-if="hasPermission('moms:report:coinrevenueexport')"></down-center>
  </div>
</template>

<script>
import '../../report.less'
import { coinDaily, coinDailyExport, coinDetailDailyExport } from '@/api/report/finance'
import { formatAmount } from '@/libs/tools'
import { rowSpanTable, formatRowspanData } from '@/libs/rowspan'
import { blobToXls } from '@/libs/blobToXls'
// import vueTreeselectShop from '@/components/vue-treeselect-shop'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
import dayjs from 'dayjs'
import saasPoptip from '@/components/saas-poptip'
import DownCenter from '@/view/components/down-center/index.vue'
export default {
  name: 'report_finance_coinrevenue',
  components: { vueTreeselectChoice, datePickerYmd, saasPoptip, DownCenter },
  data () {
    return {
      dataChoose: 'day',
      ShopValue: [],
      timeDate: [dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00'), dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00')],
      selectDateType: 'date',
      dataType: [{ key: 'date', value: '日' }, { key: 'month', value: '月' }, { key: 'year', value: '年' }],
      tableHeight: 0,
      shopName: null,
      options: [],
      testValue: [],
      value: null,
      statusList: false,
      isloading: false,
      shopList: [],
      dateOption: {
        disabledDate: date => {
          if (process.env.NODE_BUILD === 'prod') return dayjs(date).isAfter(dayjs(new Date()).subtract(1, 'day'))
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      total: 0,
      searchObj: {
        shopId: [],
        startDate: '',
        endDate: '',
        offset: 1,
        limit: 10
      },
      resData: [
      ],
      columns: [
        { title: '门店', key: 'shopName', align: 'center', width: 185, fixed: 'left' },
        { title: '游戏币营收(元)', key: 'coinSaleAmount', align: 'center', width: 150 },
        { title: '游戏币售赠(枚)', key: 'coinGiftNum', align: 'center', width: 150 },
        { title: '机台吸币总数(枚)', key: 'machineReceiveNum', align: 'center', width: 150 },
        { title: '期末存币总数(枚)', key: 'depositNum', align: 'center', width: 150, slot: 'depositNum' },
        { title: '单位币值(元)', key: 'unitCoinAmount', align: 'center', width: 150, slot: 'unitCoinAmount' },
        { title: '期末存币金额(元)', key: 'depositAmount', align: 'center', width: 140, slot: 'depositAmount' },
        {
          title: '币值收入(元)',
          align: 'center',
          children: [
            { title: '合计', key: 'totalAmount', align: 'center', width: 150 },
            { title: '游戏收入', key: 'gameAmount', align: 'center', width: 150 },
            { title: '商品销售', key: 'productSaleAmount', align: 'center', width: 150 },
            { title: '出租收入', key: 'rent', align: 'center', width: 150 }
          ]
        },
        { title: '操作', slot: 'action', align: 'center', width: 150 }
      ]
    }
  },
  computed: {
    startDate () {
      return this.timeDate[0]
    },
    endDate () {
      return this.timeDate[1]
    },
    depositNnmMonth () {
      if (dayjs(new Date()).format('YYYY-MM') === dayjs(this.timeDate[0]).format('YYYY-MM')) return `取值是${dayjs(new Date()).subtract(1, 'day').format('YYYY-MM-DD')}日的数据`
      return `取值是${dayjs(this.timeDate[1]).subtract(1, 'day').format('YYYY-MM-DD')}日的数据`
    },
    depositNnmDate () {
      if (dayjs(new Date()).format('YYYY') === dayjs(this.timeDate[0]).format('YYYY')) return `取值是${dayjs(new Date()).subtract(1, 'day').format('YYYY-MM-DD')}日的数据`
      return `取值是${dayjs(this.timeDate[1]).subtract(1, 'day').format('YYYY-MM-DD')}日的数据`
    }
  },
  mounted () {
    // this.getShopList()
  },
  updated () {
    this.$nextTick(() => {
      rowSpanTable(this.$refs.rowSpanTable, 'shopName', 'left')
    })
  },
  watch: {
    dataChoose (val) {
      // console.log(val)
    }
  },
  methods: {
    async handleShop () {
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.searchObj.shopId = ids
      this.searchCoin()
    },
    apiFinish () {
      this.ShopValue = null
    },
    // 导出
    DropdownItemn (val) {
      let obj = { 'date': '0', 'month': '1', 'year': '2' }
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.$refs.downCenterRef.addTask({
          merchantId: this.$store.state.user.merchantId,
          shopIds: this.searchObj.shopId,
          startDate: this.startDate,
          endDate: this.endDate,
          dateType: obj[this.selectDateType],
          taskModule: val
        })
        // this.exportTable(obj[this.selectDateType], val)
      }
    },
    exportTable (type, val) {
      if (val === '1') {
        coinDailyExport({
          merchantId: this.$store.state.user.merchantId,
          // shopIds: this.searchObj.shopId,
          shopIds: this.searchObj.shopId,
          startDate: this.startDate,
          endDate: this.endDate
        }).then(res => {
          if (res.status === 200) {
            if (type === '0') {
              blobToXls(res.data, `游戏币收入汇总表(${this.startDate.substring(0, 10)})`)
            } else if (type === '1') {
              blobToXls(res.data, `游戏币收入汇总表(${this.startDate.substring(0, 7)})`)
            } else {
              blobToXls(res.data, `游戏币收入汇总表(${this.startDate.substring(0, 4)})`)
            }
          } else {
            this.$Message.error(`${res.error}`)
          }
        })
      } else {
        coinDetailDailyExport({
          merchantId: this.$store.state.user.merchantId,
          // shopIds: this.searchObj.shopId,
          shopIds: this.searchObj.shopId,
          startDate: this.startDate,
          endDate: this.endDate,
          dateType: type
        }).then(res => {
          if (res.status === 200) {
            if (type === '0') {
              blobToXls(res.data, `游戏币收入明细表(${this.startDate.substring(0, 10)})`)
            } else if (type === '1') {
              blobToXls(res.data, `游戏币收入明细表(${this.startDate.substring(0, 7)})`)
            } else {
              blobToXls(res.data, `游戏币收入明细表(${this.startDate.substring(0, 4)})`)
            }
          } else {
            this.$Message.error(`${res.error}`)
          }
        })
      }
    },
    // 获取游戏币数据
    getCoinDaily () {
      this.isloading = true
      this.tableHeight = 0
      coinDaily({
        merchantId: this.$store.state.user.merchantId,
        shopIds: this.searchObj.shopId,
        startDate: this.startDate,
        endDate: this.endDate,
        offset: (this.searchObj.offset - 1) * this.searchObj.limit,
        limit: this.searchObj.limit
      }).then(res => {
        this.isloading = false
        if (res.data.status === 200) {
          this.total = res.data.totalCount
          if (res.data.data && res.data.data.length >= 14) {
            this.tableHeight = 520
          }
          this.resData = res.data.data ? formatRowspanData('shopName', this.filtersresData(res.data.data)) : []
          // this.$nextTick(() => {
          //   rowSpanTable(this.$refs.rowSpanTable, 'shopName', 'left')
          // })
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    filtersresData (data) {
      data.map(ele => {
        Object.keys(ele).forEach(key => {
          if (key !== 'shopName' && key !== 'shopId' && key !== 'coinGiftNum' && key !== 'machineReceiveNum' && key !== 'depositNum') {
            ele[key] = formatAmount(ele[key])
          }
        })
      })
      return data
    },
    // 查询
    searchCoin () {
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.searchObj.offset = 1
        this.searchObj.limit = 10
        this.getCoinDaily()
      }
    },
    // 获取页码
    handlePage (val) {
      this.searchObj.offset = val
      this.getCoinDaily()
    },
    handlePageSize (pageSize) {
      this.searchObj.limit = pageSize
      this.getCoinDaily()
    },
    skipDetail (idx) {
      localStorage.setItem('obj', JSON.stringify({ id: [idx], type: this.selectDateType, timeDate: this.timeDate, selectDateType: this.selectDateType }))
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.$router.push({
          name: 'report_finance_coinrevenue_detail',
          params: { id: 1 }
        })
      }
    }
  }
}
</script>
<style>
#coinrevenue-des .ropdown .ivu-select-dropdown {
  left: -56px !important;
}
</style>
